package com.yuke.cloud.service.smc.job;

import com.yuke.cloud.service.api.omc.dto.DmsStoreOrderApi;
import com.yuke.cloud.service.api.omc.service.OmcOrderFeignApi;
import com.yuke.cloud.service.smc.entity.DmsStore;
import com.yuke.cloud.service.smc.service.DmsStoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 定时清空服务人，当该业务员服务店铺一个月下单金额变少时，要更换跟进人。
 * @author: 金天
 */
@Component
@Slf4j
@EnableScheduling
public class ClearServiceUserIdQuartz {

    @Resource
    private DmsStoreService dmsStoreService;

    @Resource
    private OmcOrderFeignApi omcOrderFeignApi;

    /**
     * 每天业务员服务人清空
     * 每天一点
     */
    @Scheduled(cron =  "0 0 1 * * ?")
    public void scheduledMethod() {
        {
            //以分为单位
            Long money = 20000L;

            List<DmsStoreOrderApi> dmsStoreOrderApis = new ArrayList<>();
            //当前时间往前推31天
            int num = 31;

            //获取当前时间
            Calendar ca = Calendar.getInstance();
            // num为天数，可以改变的
            ca.add(Calendar.DATE, -num);
            Date endDate = ca.getTime();

            //followTime小于等于endDate 即 有服务人 服务了三十一天及以上的店铺
            List<DmsStore> list = dmsStoreService.findServiceStoreByTime(endDate);

            //new 新的list
            for (DmsStore dmsStore : list) {
                DmsStoreOrderApi dmsStoreOrderApi = new DmsStoreOrderApi();
                dmsStoreOrderApi.setShopId(dmsStore.getShopId());
                dmsStoreOrderApi.setFollowTime(dmsStore.getFollowTime());
                dmsStoreOrderApi.setStoreId(dmsStore.getStoreId());
                dmsStoreOrderApis.add(dmsStoreOrderApi);
            }


            //followTime至今的总金额
            List<DmsStoreOrderApi> odsOrderApiDtos = omcOrderFeignApi.countByDmsStore(dmsStoreOrderApis);

            if (odsOrderApiDtos.size()>0&&odsOrderApiDtos!=null) {

                //将得到的金额赋给原list
                for (DmsStoreOrderApi odsOrderApiDto : odsOrderApiDtos) {
                    for (DmsStoreOrderApi dmsStoreOrderApi : dmsStoreOrderApis) {
                        if (odsOrderApiDto.getShopId().equals(dmsStoreOrderApi.getShopId())) {
                            dmsStoreOrderApi.setAmountPayable(odsOrderApiDto.getAmountPayable());
                            if (dmsStoreOrderApi.getAmountPayable() == null || dmsStoreOrderApi.getAmountPayable().longValue() < money) {
                                dmsStoreService.quitServiceStore(dmsStoreOrderApi.getStoreId());
                            }
                        }
                    }
                }
            }
        }
    }
}
